﻿using MQ.Core.Cache;
using MQ.Core.Common;
using MQ.Core.Entity.System;
using MQ.Core.IRepository.System;
using MQ.Core.IService.System;
using MQ.Core.Model;
using MQ.Core.Util;
using System;
using System.Collections.Generic;
using System.Text;

namespace MQ.Core.Service.System
{
    public class AreaService : IAreaService
    {
        private readonly IAreaRepository areaRepository;
        private const string AREA_CACHE = "SYS:AREA:";//cache prefix
        private ICache cache = CacheFactory.Redis();
        public AreaService(IAreaRepository areaRepository)
        {
            this.areaRepository = areaRepository;
        }

        public void Delete(string ids)
        {
            areaRepository.Delete(ids);
            cache.Remove(AREA_CACHE + "TREE");//清除缓存
        }

        public void Delete(long id)
        {
            areaRepository.Delete(id);
            cache.Remove(AREA_CACHE + "TREE");//清除缓存
        }

        public void Delete(List<long> ids)
        {
            areaRepository.Delete(ids);
            cache.Remove(AREA_CACHE + "TREE");//清除缓存
        }

        public IEnumerable<AreaEntity> GetList(string query)
        {
            return areaRepository.GetList(query);
        }

        public IEnumerable<AreaEntity> GetPageList(Pagination pagination, string query)
        {
            throw new NotImplementedException();
        }
        [Cache(AREA_CACHE+"TREE",false)]
        public IEnumerable<TreeModel> GetTree()
        {
            //var data = cache.Get<List<TreeModel>>(AREA_CACHE + "TREE");
            //if (data != null) return data;
            var list = GetList("");
            List<TreeModel> trees = new List<TreeModel>();
            foreach(var item in list)
            {
                trees.Add(new TreeModel() { code=item.Code,pcode=item.ParentCode,text=item.Name,value=item.Code});
            }
            //data = trees.ToTree();
            //cache.Set(AREA_CACHE + "TREE", data);
            return trees.ToTree();
        }

        public void Save(AreaEntity entity)
        {
            if (entity.Id > 0) areaRepository.Update(entity);
            else areaRepository.Add(entity);
            cache.Remove(AREA_CACHE + "TREE");//清除缓存
        }
    }
}
